<template>
  <div class="category">
    <el-card>
      <el-tree :data="dataSource" node-key="id" :props="part" :expand-on-click-node="false" :default-expand-all='true'>
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <div>
              <el-image :src='data.picUrl' style="width:30px;height:auto;vertical-align: middle" v-if="data.level==2&&data.picUrl" />
              <span>{{ node.label }} </span>
              <el-tag v-if="!(data.level==-1)" :type="data.level?data.level==1?'warning':'success':'danger'">{{data.level?data.level==1?'二级':'三级':'一级'}}</el-tag>
            </div>
            <span>
              <el-button type='primary' size='small' round @click="appendOrEdit(data,true)" v-btnkey='"product:category:create"' v-if="data.level<2"> 添加 </el-button>
              <el-button type='warning' size='small' round @click="appendOrEdit(data,false)" v-btnkey='"product:category:edit"' v-if="data.level!=-1"> 编辑 </el-button>
              <el-button type='danger' size='small' round @click="remove(data)" v-btnkey='"product:category:delete"' v-if="!data.childrenList"> 删除 </el-button>
            </span>
          </span>
        </template>
      </el-tree>
    </el-card>
    <!-- 弹出对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="bool?'添加':'修改'" :destroy-on-close='true' >
      <el-form :model="form" ref="formRef" @submit.prevent.nactive>
        <el-form-item label="类目名称" prop='title' :label-width="formLabelWidth" :rules="[{required:true, message:'请输入标题',trigger:'blur'}]">
          <el-input v-model="form.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="类目图片" :label-width="formLabelWidth">
          <el-upload class="avatar-uploader" :headers='myHeaders' :action="imgPath" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="form.picUrl" :src="form.picUrl" class="avatar" />
            <div class="box" v-else></div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="confirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import { post, imgUrl } from "@/utils/http";
export default {
  data() {
    return {
      dataSource: [],
      part: {  //子集配置
        label: 'title',
        value: 'id',
        children: 'childrenList'
      },
      dialogFormVisible: false,  //显示弹出框
      formLabelWidth: '140px',
      form: {  //表单数据
        title: '',
        picUrl: '',
        parentId: ''
      },
      imgPath: imgUrl,  //图片地址
      myHeaders: { AdminToken: Cookies.get('token') },  //图片上传请求头
      bool: true //添加还是修改
    }
  },
  methods: {
    initData() {
      post({ _gp: 'admin.category', _mt: 'categoryTree' }).then(res => {
        if (200 == res.errno) {
          this.dataSource = [
            {
              title: '全部类目',
              level: -1,
              childrenList: [...res.data]
            }
          ]
        } else {
          ElMessage.warning(errmsg)
        }
      })
    },
    // 添加 或 修改
    appendOrEdit(data, boole) {
      this.bool = boole
      this.dialogFormVisible = true
      if (boole) {
        this.form = {}
        this.form.parentId = data.id
        return
      }
      Object.assign(this.form, data)
      if (data.level != 2) this.form.picUrl = ''
    },
    // 删除
    remove(data) {
      ElMessageBox.confirm(
        '确定要删除吗?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          post({ _gp: 'admin.category', _mt: 'delete', id: data.id }).then(res => {
            if (200 == res.errno) {
              ElMessage.success('成功')
              this.initData()
            } else {
              ElMessage.warning(res.errmsg)
            }
          })
        })
    },
    // 确定
    confirm() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          if (this.bool) {
            post({ _gp: 'admin.category', _mt: 'create', ...this.form }).then(res => {
              if (200 == res.errno) {
                this.dialogFormVisible = false
                ElMessage.success('成功')
                this.initData()
              }
            })
          } else {
            post({ _gp: 'admin.category', _mt: 'update', ...this.form }).then(res => {
              if (200 == res.errno) {
                this.dialogFormVisible = false
                ElMessage.success('成功')
                this.initData()
              }
            })
          }
        }
      })
    },
    // 上传图片
    handleAvatarSuccess(res, file) {
      if (200 == res.errno) return this.form.picUrl = file.response.url  //赋值图片路径
    },
    beforeAvatarUpload(rawFile) {
      if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('图片得是jpg类型!')
        return false
      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('头像图片不能超过2MB!')
        return false
      }
      return true
    }
  },
  created() {
    this.initData()
  }
}
</script>

<style lang="less" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 18px;
}
.box {
  width: 100px;
  height: 100px;
  border: 1px dashed #ccc;
}
/deep/.el-tree-node__content {
  height: 50px;
}
.avatar {
  width: 150px;
}
.el-tag {
  margin-left: 10px;
}
/deep/.el-overlay {
  z-index: 5 !important;
}
</style>